package com.lagou.controller;

import com.lagou.entity.CourseComment;
import com.lagou.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("comment")
@CrossOrigin
public class CommentController {

    @Autowired
    private CommentService commentService;


    @GetMapping("saveCourseComment")
    public Object saveCourseComment(Integer courseid,Integer userid,String username,String comment) throws UnsupportedEncodingException {
        System.out.println(username);
        System.out.println(comment);
        System.out.println(new String(username.getBytes("ISO-8859-1"),"UTF-8"));
        System.out.println(new String(comment.getBytes("ISO-8859-1")));

       // username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
       // comment = new String(comment.getBytes("ISO-8859-1"),"UTF-8");
        //解决get情况中，传递过来的乱码问题，因为get默认是ISO-8859-1的操作，我们也使用ISO-8859-1进行变成对应的中文
        //然后设置操作UTF-8，虽然并不需要设置


        CourseComment courseComment = new CourseComment();
        courseComment.setCourseId(courseid); //课程编号
        //这里写为0，因为我们的留言只操作对应的课程，章节和小节并没有操作
        //所以这样的操作，我们称为预留字段
        //即在后面的版本中（如更新版本）进行执行，现在默认写为0，虽然写其他的也可
        courseComment.setSectionId(0); //章节编号，预留字段
        courseComment.setLessonId(0); //小节编号，预留字段
        courseComment.setUserId(userid); //用户编号
        courseComment.setUserName(username); //用户昵称
        courseComment.setParentId(0); //没有父id，预留字段
        courseComment.setComment(comment); //留言内容
        courseComment.setType(0); //0：用户留言，预留字段
        courseComment.setLastOperator(courseid); //最后操作的用户编号
        Integer integer = commentService.saveComment(courseComment);
        return integer;



    }

    @GetMapping("getCourseCommentList/{courseId}/{pageIndex}/{pageSize}")
    public List<CourseComment> getCommentsByCourseId(@PathVariable("courseId") Integer courseId, @PathVariable("pageIndex")Integer pageIndex, @PathVariable("pageSize")Integer pageSize) {
        int pagesize = pageSize; //每页条数
        int pageindex = pageIndex; //页码
        List<CourseComment> commentsByCourseId = commentService.getCommentsByCourseId(courseId, (pageindex-1)*20, pagesize);
        return commentsByCourseId;
    }

    @GetMapping("saveFavorite/{commentid}/{userid}")
    public Integer saveFavorite(@PathVariable("commentid") Integer commentid, @PathVariable("userid") Integer userid){
        Integer integer = commentService.saveFavorite(commentid, userid);
        return integer;
    }

    @GetMapping("cancelFavorite/{commentid}/{userid}")
    public Integer cancelFavorite(@PathVariable("commentid") Integer commentid,@PathVariable("userid") Integer userid){
        Integer integer = commentService.cancelFavorite(commentid, userid);
        return integer;
    }
}
